<?php	
	oh_module_header();
	
	// Interface function	
	function oh_module_excelxml($tokens) {		
		return oh_this();
	} 

	// Option file required
	//require_once(dirname(__FILE__)."/Excel/reader.php");
	
	// Main class of module
	class oh_class_excelxml {
		public $data;
		public $file;
		public $offset;

		function oh_class_excelxml() {
			$this->data = array();
			$this->offset = array("x"=>0,"y"=>0);
		}
		function load($filename) {
			$data = oh("xml")->load("test.xml");
			$rows = $data["Workbook"]["Worksheet"][0]["Table"]["Row"];
			$page = array();
			$cy = 0;
			$cx = 0;
			foreach($rows as $y=>$row) {
				$page[$y] = array();
				if (is_array($row["Cell"])) {			
					$cx = 0;
					foreach($row["Cell"] as $x=>$cell) {
						if (isset($cell["Data"])) {
							if (is_array($cell["Data"])) {
								//oh_dump($cell["Data"],"[$x,$y]");
							} else {
								//echo "[$x,$y]: ".$cell["Data"]."<br>";
								$page[$cy][$cx] = $cell["Data"];
							}
						}
						$cx++;
					}
				}
				$cy++;
			}
			$this->data = $page;
		}
		function cell($cell,$value=null) {
			if ($value===null) {
				$cell = strtoupper(trim($cell));
				$cell = explode(":",$cell);
				if (count($cell)==1) {					
					$c = $this->parse($cell[0]);
					return $this->data[$c["y"]-1-($this->offset["y"])][$c["x"]-2-($this->offset["x"])];
				} else {
					$c0 = $this->parse($cell[0]);
					$c1 = $this->parse($cell[1]);
					$oo = array();					
					$cx = 0;				
					for ($x=(int)$c0['x'];$x<=(int)$c1['x'];$x++) {
						$cy = 0;					
						$oo[$cx] = array();
						for ($y=(int)$c0['y'];$y<=(int)$c1['y'];$y++) {
							$value = $this->data[$y-1-($this->offset["y"])][$x-2-($this->offset["x"])];
							//$value = isset($value) ? $value : "";
							$oo[$cx][$cy] = $value;
							$cy++;
						}
						$cx++;
					}
					return $oo;
				}				
			} else {
				return oh_this();
			}
		}

		function showdata() {
			oh_dump(
				$this->data
			);
		}


		function info() {
			echo 'xls:module:info';
		}
		
		function parse($cell) {
			preg_match_all("/([A-Z]+)([0-9]+)/",$cell,$result);
			$x = $this->letter2number($result[1][0]);
			$y = (int)$result[2][0];
			$o = array("x"=>$x,"y"=>$y,"original"=>$cell);
			return $o;
		}
		function letter2number($s) {
			$s = strtoupper(trim($s));
			$t = 0;
			for($i=0;$i<strlen($s);$i++) {
				$v = (ord($s{$i})-64);
				$e = pow(26,(strlen($s)-$i-1));
				$t += $e * $v;
				//echo "V:$v E:$e <br>";
			}
			return $t;
		}
	}
	
	// Main object of module
	global $oh_object_excelxml;
	$oh_object_excelxml = new oh_class_excelxml();
?>
